<?php 
class deptClassAction extends ActionManage
{
	public function defaultAction()
	{
		
	}
	
	public function dataAction()
	{
		$sort = $this->get('sort');
		$dir  = $this->get('dir');
		$order= '`sort` asc';
		if($sort && $dir)$order= '`'.$sort.'` '.$dir.'';
		
		
		$this->drows	= array();
		$rows = m('dept')->getall('`cid`='.$this->companyid.'','*', $order);
		$total = count($rows);
		$this->getdepts($rows,0, 1);
		
		
		$barr  = array(
			'rows' => $this->drows,
			'totalCount'=> $total,
			'success' => true,
		);
		return $barr;
	}
	private function getdepts($rows, $pid, $oi)
	{
		$len = 0;
		foreach($rows as $k=>$rs){
			if($rs['pid']==$pid){
				$rs['level'] = $oi;
				$this->drows[] = $rs;
				$cdus = count($this->drows)-1;
				$len++;
				$cdu = $this->getdepts($rows,$rs['id'], $oi+1);
				$this->drows[$cdus]['stotal'] = $cdu;
			}
		}
		return $len;
	}
	
	public function formAction()
	{
		$id = (int)$this->get('id','0');
		$this->smartydata['id'] = $id;
		$rs['name'] = '';
		$rs['num']  = '';
		$rs['headman']  = '';
		$rs['headid']   = '';
		$rs['pid']  = $this->get('pid','0');
		$rs['sort'] = '0';
		if($id>0){
			$rs = m('dept')->getone('`id`='.$id.' and `cid`='.$this->companyid.'');
		}
		$this->smartydata['rs'] = $rs;
	}
	
	public function savecheckAction()
	{
		$name = $this->post('name');
	
		$id  = (int)$this->post('id','0');
		$pid = (int)$this->post('pid','0');
		if($pid==0){
			if($id!=1)return '顶级只能有一个';
		}
		$uarr= array(
			'name' 	=> $name,
			'cid'	=> $this->companyid,
			'optdt'	=> $this->now,
			'pid'	=> $pid,
			'sort' 	=> (int)$this->post('sort'),
		);
		
		$where = '`id`='.$id.' and `cid`='.$this->companyid.'';
		if($id==0){
			$where = '';
			$maxid = m('dept')->getmou('max(id)','`cid`='.$this->companyid.'');
			$uarr['id'] = floatval($maxid)+1;
		}
		
		$bo 	= m('dept')->record($uarr, $where);
		if(!$bo)return $this->db->error();
		
		return 'ok';
	}
	
	public function deldeptAction()
	{
		$id = (int)$this->post('id','0');
		if($id<1)return returnerror('无效ID');
		$to = m('dept')->rows('`cid`='.$this->companyid.' and `pid`='.$id.'');
		if($to>0)return returnerror('有下级部门不能删');
		m('dept')->delete('`cid`='.$this->companyid.' and `id`='.$id.'');
		return returnsuccess();
	}
}